"use client"
import { useEffect, useRef, useState } from 'react';
import { Canvas, FabricText, FabricImage, Line,FabricObject,Gradient,Shadow ,TEvent,Textbox} from 'fabric';
import { toast } from '@/hooks/use-toast'
import Toolbar from '@/components/cover/Toolbar';
import PropertyPanel from '@/components/cover/PropertyPanel';

// @ts-ignore
import WebFont from 'webfontloader';
import {
  TooltipProvider
} from "@/components/ui/tooltip"


interface Tool {
  text: string;
  url: string;
}

interface Template {
  name: string;
  image: string;
  title: string;
  json: string;
  ispc:boolean;
}



const HomePage = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [canvas, setCanvas] = useState<Canvas | null>(null);
  const [isPc, setIsPc] = useState(true);
  const [bgColor, setBgColor] = useState('#FFFFFF');
  const [showGrid, setShowGrid] = useState(false);
  const [selectedObject, setSelectedObject] = useState<FabricObject | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  
  useEffect(() => {
    // 加载自定义字体
    if (typeof window !== 'undefined') {
     // 只在客户端加载字体
        WebFont.load({
          google: {
            families: [
              'Open Sans:400,700',
              'Roboto:400,700',
              'Lato:400,700',
              'Montserrat:400,700',
              'Raleway:400,700',
              'Poppins:400,700',
              'Noto Sans:400,700'
            ]
          },
          custom: {
            families: [
              '优设标题黑',
              '锐字真言体',
              '站酷文艺体',
              '站酷快乐体',
              '胡晓波男神体',
              '仓耳小丸子',
              '阿里巴巴普惠体-Bold',
              '思源宋体-Bold'
            ], 
            urls: [
              '/fonts/youshebiaotihei.css', // 字体文件的路径
              '/fonts/YueZiZhenYan.css',
              '/fonts/ZhanKuWenYiTi.css',
              '/fonts/ZhanKuKuaiLe.css',
              '/fonts/huxiaobonanshen.css',
              '/fonts/xiaowanzi.css',
              '/fonts/alipuhui_2_85_bold.css',
              '/fonts/SourceHanSerifCN-Bold.css'
            ]
          },
          active: () => {
            console.log('字体加载完成'); // 添加调试信息
          },
          inactive: () => {
            console.log('字体加载失败'); // 添加错误处理
          }
        });
      }
  }, []);

  // 修改字体选择器
  const fontOptions = [
    '优设标题黑', 
    '锐字真言体',
    '站酷文艺体',
    '站酷快乐体',
    '胡晓波男神体',
    '仓耳小丸子',
    '阿里巴巴普惠体-Bold',
    '思源宋体-Bold',
    'Open Sans',  
    'Roboto',    
    'Lato',      
    'Montserrat',
    'Raleway',   
    'Poppins',   
    'Noto Sans'  
  ];

  const [textItem, setTextItem] = useState({
    fontSize: 80,
    fontFamily: '优设标题黑',
    textColor: '#FFA500',
    fontWeight: 500,
    stroke: '#000000',
    strokeWidth: 0,
    shadow: {
      color: 'rgba(0,0,0,0.5)',
      blur: 5,
      offsetX: 2,
      offsetY: 2
    }
  });

  const [imageItem, setImageItem] = useState({
    scaleX: 0.5,
    scaleY: 0.5,
    stroke: '#000000',
    strokeWidth: 0,
    shadow: {
      color: 'rgba(0,0,0,0.5)',
      blur: 5,
      offsetX: 2,
      offsetY: 2,
    }
  });
  const [templates, setTemplates] = useState<Template[]>([]);


  useEffect(() => {
    setTemplates([
      {
        name: '极简课程模板',
        title: '极简课程模板', 
        image:'/images/极简课程模板.png',
        json: '/json/极简课程模板.json',
        ispc: true
      },
      {
        name: '系列教程模板',
        title: '教程模板',
        image:'/images/系列教程模板.png',
        json: '/json/系列教程模板.json',
        ispc: true
      },
      {
        name: '科技数码模板',
        title: '科技数码模板', 
        image:'/images/科技数码模板.png',
        json: '/json/科技数码模板.json',
        ispc: true
      },
      {
        name: '手机端课程模板',
        title: '手机端课程模板',
        image:'/images/手机端课程模板.png',
        json: '/json/手机端课程模板.json',
        ispc: false
      },
     
    ]);
  }, []);


  const tools: Tool[] = [
    { text: '图片去背景', url: 'https://cutout.aiwave.cc/' },
    { text: '截图美化', url: 'https://shots.so/' },
    { text: '产品图制作', url: 'https://www.x-design.com/product-shoot' },
    { text: '图标素材', url: 'https://www.iconfont.cn/' },
  ];

  useEffect(() => {
    if (canvasRef.current) {
      const newCanvas = new Canvas(canvasRef.current, {
        width: isPc ? 1200 : 720*3/5,
        height: isPc ? 720 : 1200*3/5,
        backgroundColor: new Gradient({
          type: 'linear',
          coords: {
            x1: 0,
            y1: 0,
            x2: isPc ? 1200 : 720,
            y2: 0
          },
          colorStops: [
            { offset: 0, color: '#FF6688' },  // 降低饱和度的粉色
            { offset: 1, color: '#AA66CC' }   // 降低饱和度的紫色
          ]
        }),
        selection: true
      });
      newCanvas.renderAll()
      setCanvas(newCanvas);

      return () => {
        newCanvas.dispose();
      };
    }
  }, [isPc]);


useEffect(() => {
  if (canvas) {
    if (showGrid) {
      // 添加网格
      const gridSize = 10;
      const gridColor = 'rgba(0,0,0,0.1)';
      const width = canvas.getWidth();
      const height = canvas.getHeight();
      
      // 创建垂直线
      for (let i = 0; i <= width; i += gridSize) {
        canvas.add(new Line([i, 0, i, height], {
          stroke: gridColor,
          selectable: false,
          evented: false
        }));
      }
      
      // 创建水平线
      for (let i = 0; i <= height; i += gridSize) {
        canvas.add(new Line([0, i, width, i], {
          stroke: gridColor,
          selectable: false,
          evented: false
        }));
      }
    } else {
      // 移除网格
      canvas.getObjects().forEach(obj => {
        if (obj.type === 'line') {
          canvas.remove(obj);
        }
      });
    }
    canvas.renderAll();
  }
}, [showGrid, canvas]);

useEffect(() => {
  if (canvas) {
    const handleSelection = () => {
      const activeObject = canvas.getActiveObject();
      // console.log('Selected object:', activeObject); // 调试信息
      setSelectedObject(activeObject || null);

       // 同步状态到输入框
       if (activeObject && activeObject.type === 'textbox') {
        const textObj = activeObject as Textbox;
        setTextItem({
          fontSize: textObj.fontSize || 80,
          fontFamily: textObj.fontFamily || '优设标题黑',
          textColor: textObj.fill?.toString() || '#FFA500',
          fontWeight: Number(textObj.fontWeight) || 500,
          stroke: textObj.stroke?.toString() || '#000000',  // Add this
          strokeWidth: textObj.strokeWidth || 0,           // Add this
          shadow: {
            color: textObj.shadow?.color || 'rgba(0,0,0,0.5)',
            blur: textObj.shadow?.blur || 5,
            offsetX: textObj.shadow?.offsetX || 2,
            offsetY: textObj.shadow?.offsetY || 2
          },
        });
      } else if (activeObject && activeObject.type === 'image') {
        const imgObj = activeObject as FabricImage;
          setImageItem({
            scaleX: imgObj.scaleX || 0.5,
            scaleY: imgObj.scaleY || 0.5,
            stroke: imgObj.stroke?.toString() || '#000000',
            strokeWidth: imgObj.strokeWidth || 0,
            shadow: {
              color: imgObj.shadow?.color || 'rgba(0,0,0,0.5)',
              blur: imgObj.shadow?.blur || 5,
              offsetX: imgObj.shadow?.offsetX || 2,
              offsetY: imgObj.shadow?.offsetY || 2
            }
          });
      }
    };


    canvas.on('selection:created', handleSelection);
    canvas.on('selection:updated', handleSelection);
    canvas.on('selection:cleared', () => {
      console.log('Selection cleared'); // 调试信息
      setSelectedObject(null);
    });

    return () => {
      canvas.off('selection:created', handleSelection);
      canvas.off('selection:updated', handleSelection);
      canvas.off('selection:cleared');
    };
  }
}, [canvas]);

const changeLinearBgColor = (color: string) => {
  if (!canvas) return;

  // Extract color stops from gradient string
  const colorStops = color.match(/#[0-9a-fA-F]{6}|rgb\([^)]+\)/g) || [];
  
  // Extract angle from gradient string
  const angleMatch = color.match(/(\d+)deg/);
  const angle = angleMatch ? parseInt(angleMatch[1]) : 0;
  
  // Convert angle to radians
  const radians = (angle * Math.PI) / 180;
  
  // Calculate gradient direction based on angle
  const width = canvasRef.current?.parentElement?.clientWidth || 1200;
  const height = canvas.getHeight();
  const x2 = Math.cos(radians) * width;
  const y2 = Math.sin(radians) * height;

  // Create gradient configuration
  const gradientConfig = {
    type: 'linear' as const,
    coords: {
      x1: 0,
      y1: 0,
      x2: x2,
      y2: y2
    },
    colorStops: colorStops.map((color, index, arr) => ({
      offset: index / (arr.length - 1),
      color: color
    }))
  };

  // Set background with gradient
  canvas.set('backgroundColor', new Gradient(gradientConfig));
  canvas.renderAll();
};

const handleCopy = async () => {
  if (!canvas) return;
  
  const activeObject = canvas.getActiveObject();
  if (!activeObject) {
    toast({
      title: "请先选择一个对象",
      variant: "destructive",
    });
    return;
  }

  try {
    const cloned = await activeObject.clone();
    cloned.set({
      left: (activeObject.left || 0) + 10,
      top: (activeObject.top || 0) + 10
    });
    canvas.add(cloned);
    canvas.setActiveObject(cloned);
    canvas.renderAll();
    toast({
      title: "复制成功",
      variant: "default",
    });
  } catch (error) {
    console.error('复制失败:', error);
    toast({
      title: "复制失败",
      variant: "destructive",
    });
  }
};


const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
  const file = e.target.files?.[0];
  if (!file || !canvas) return;

  const reader = new FileReader();
  reader.onload = (event) => {
    const img = new Image();
    img.src = event.target?.result as string;
    
    img.onload = () => {
      const fabricImage = new FabricImage(img, {
        left: isPc ? 400 : 220,
        top: 200,
        scaleX: imageItem.scaleX,  // 使用 imageItem 的 scaleX
        scaleY: imageItem.scaleY,  // 使用 imageItem 的 scaleY
        stroke: imageItem.stroke,  // 使用 imageItem 的 stroke
        strokeWidth: imageItem.strokeWidth,  // 使用 imageItem 的 strokeWidth
        shadow: new Shadow(imageItem.shadow)  // 使用 imageItem 的 shadow
      });
      canvas.add(fabricImage);
      canvas.renderAll();
    };
  };
  reader.readAsDataURL(file);
};



  const setSize = (size: 'pc' | 'phone') => {
    setIsPc(size === 'pc');
  };

  const addText = () => {
    if (canvas) {
      const text = new Textbox('修改文本', {
        left: isPc ? 400 : 220,
        top: 200,
        fontSize: textItem.fontSize,
        fontFamily: textItem.fontFamily,
        fill: textItem.textColor,
        fontWeight: Number(textItem.fontWeight),
        stroke: textItem.stroke,
        strokeWidth: textItem.strokeWidth,
        shadow: new Shadow({
          color: textItem.shadow.color,
          blur: textItem.shadow.blur,
          offsetX: textItem.shadow.offsetX,
          offsetY: textItem.shadow.offsetY
        }),
        editable: true,
        hasControls: true,
        hasBorders: true,
        editingBorderColor: 'blue',
        splitByGrapheme: true ,
        width: 400, 
      });
      text.enterEditing();
     

      canvas.add(text);
      canvas.setActiveObject(text);
      canvas.renderAll();
    }
  };


  const clearBg = () => {
    if (canvas) {
      canvas.backgroundColor='#fff'
      canvas.renderAll();
    }
  };

  const applyTemplate = async (template: Template) => {
    try {
      const response = await fetch(template.json);
      const json = await response.json();
      if (canvas) {
        canvas.clear();
        // 根据模板的ispc属性调整画布尺寸
          const newWidth = template.ispc ? 1200 : 720*3/5;
          const newHeight = template.ispc ? 720 : 1200*3/5;
          
          // 立即设置画布尺寸
          canvas.setDimensions({
            width: newWidth,
            height: newHeight
          });
        

        await canvas.loadFromJSON(json);
        canvas.requestRenderAll();
        toast({
          title: `应用模板: ${template.title}`,
          variant: "default",
        });
         // 关闭对话框
      setDialogOpen(false); // Add this line
      }
    } catch (error) {
      console.error('应用模板失败:', error);
      toast({
        title: "应用模板失败",
        variant: "destructive",
      });
    }
  };

  
interface HistoryItem {
  action: 'add' | 'remove' | 'modify';
  object: FabricObject;
  state?: any;
}

const [undoHistory, setUndoHistory] = useState<HistoryItem[]>([]);
const [redoHistory, setRedoHistory] = useState<HistoryItem[]>([]);

const addToHistory = (action: HistoryItem['action'], object: FabricObject) => {
  const clonedObject = object.toObject();
  setUndoHistory(prev => [...prev, { action, object, state: clonedObject }]);
  setRedoHistory([]); // 清空重做历史
};

useEffect(() => {
  if (canvas) {
    // 定义事件处理函数
    const handleAdded = (e: { target: FabricObject }) => {
      if (e.target) {
        addToHistory('add', e.target);
      }
    };

    const handleRemoved = (e: { target: FabricObject }) => {
      if (e.target) {
        addToHistory('remove', e.target);
      }
    };

    const handleModified = (e: { target: FabricObject }) => {
      if (e.target) {
        addToHistory('modify', e.target);
      }
    };

    // 添加事件监听
    canvas.on('object:added', handleAdded);
    canvas.on('object:removed', handleRemoved);
    canvas.on('object:modified', handleModified);

    return () => {
      // 移除事件监听
      canvas.off('object:added', handleAdded);
      canvas.off('object:removed', handleRemoved);
      canvas.off('object:modified', handleModified);
    };
  }
}, [canvas]);


const handleAdded = (e: { target: FabricObject }) => {
  if (e.target) addToHistory('add', e.target);
};
const handleRemoved = (e: { target: FabricObject }) => {
  if (e.target) addToHistory('remove', e.target);
};
const handleModified = (e: { target: FabricObject }) => {
  if (e.target) addToHistory('modify', e.target);
};

const handleUndo = () => {
  if (undoHistory.length > 0 && canvas) {
    // 暂停历史记录
    canvas.off('object:added');
    canvas.off('object:removed');
    canvas.off('object:modified');

    const lastAction = undoHistory[undoHistory.length - 1];
    setUndoHistory(prev => prev.slice(0, -1));
    setRedoHistory(prev => [...prev, lastAction]);

    switch (lastAction.action) {
      case 'add':
        canvas.remove(lastAction.object);
        break;

      case 'remove':
        canvas.add(lastAction.object);
        break;

      case 'modify':
        if (lastAction.state) {
          lastAction.object.set(lastAction.state);
          lastAction.object.setCoords();
        }
        break;
    }

    // 恢复历史记录
    canvas.on('object:added', handleAdded);
    canvas.on('object:removed', handleRemoved);
    canvas.on('object:modified', handleModified);

    canvas.requestRenderAll();
  }
};


const handleRedo = () => {
  if (redoHistory.length > 0 && canvas) {
    // 暂停历史记录
    canvas.off('object:added');
    canvas.off('object:removed');
    canvas.off('object:modified');

    const lastAction = redoHistory[redoHistory.length - 1];
    setRedoHistory(prev => prev.slice(0, -1));
    setUndoHistory(prev => [...prev, lastAction]);

    switch (lastAction.action) {
      case 'add':
        canvas.add(lastAction.object);
        break;

      case 'remove':
        canvas.remove(lastAction.object);
        break;

      case 'modify':
        if (lastAction.state) {
          lastAction.object.set(lastAction.state);
          lastAction.object.setCoords();
        }
        break;
    }

    // 恢复历史记录
    canvas.on('object:added', handleAdded);
    canvas.on('object:removed', handleRemoved);
    canvas.on('object:modified', handleModified);

    canvas.requestRenderAll();
  }
};

useEffect(() => {
  const handleKeyDown = (e: KeyboardEvent) => {
    if (!canvas) return;

    const activeObject = canvas.getActiveObject();
    
 
    // 处理文本编辑相关按键
    if (activeObject && activeObject.type === 'textbox') {
      const textbox = activeObject as Textbox;
      
      // 如果正在编辑文本，允许正常输入
      if (textbox.isEditing) {
        // 只阻止全局快捷键
        if ((e.ctrlKey || e.metaKey) && (e.key === 'c' || e.key === 'z' || e.key === 'Z')) {
          e.preventDefault();
        }
        return;
      }

      // 处理全局快捷键
      e.preventDefault();

      // 复制 Ctrl+C / Cmd+C
      if ((e.ctrlKey || e.metaKey) && e.key === 'c') {
        handleCopy();
      }
      // 撤销 Ctrl+Z / Cmd+Z
      else if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
        handleUndo();
      }
      // 重做 Ctrl+Shift+Z / Cmd+Shift+Z
      else if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'Z') {
        handleRedo();
      }
      return;
    }

    // 处理全局快捷键
    e.preventDefault();

    // 复制 Ctrl+C / Cmd+C
    if ((e.ctrlKey || e.metaKey) && e.key === 'c') {
      handleCopy();
    }
    // 撤销 Ctrl+Z / Cmd+Z
    else if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
      handleUndo();
    }
    // 重做 Ctrl+Shift+Z / Cmd+Shift+Z
    else if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'Z') {
      handleRedo();
    }
    // 上下左右移动
    else if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
      if (activeObject) {
        const delta = 1; // 移动步长
        const newTop = activeObject.top || 0;
        const newLeft = activeObject.left || 0;

        if (e.key === 'ArrowUp') activeObject.set('top', newTop - delta);
        else if (e.key === 'ArrowDown') activeObject.set('top', newTop + delta);
        else if (e.key === 'ArrowLeft') activeObject.set('left', newLeft - delta);
        else if (e.key === 'ArrowRight') activeObject.set('left', newLeft + delta);

        canvas.renderAll();
      }
    }
  };

  document.addEventListener('keydown', handleKeyDown);
  return () => {
    document.removeEventListener('keydown', handleKeyDown);
  };
}, [canvas]);



return (
  <div className="w-full mx-auto px-8 sm:px-6 md:px-12 lg:px-24 xl:border xl:border-gray-200 text-base md:text-lg">
    <TooltipProvider>
      <div className="pt-4">
        {/* 替换工具栏 */}
        <Toolbar
          isPc={isPc}
          canvas={canvas}
          showGrid={showGrid}
          undoHistory={undoHistory}
          redoHistory={redoHistory}
          templates={templates}
          dialogOpen={dialogOpen}
          onSetSize={setSize}
          onClearBg={clearBg}
          onAddText={addText}
          onImageUpload={handleImageUpload}
          onToggleGrid={() => setShowGrid(!showGrid)}
          onUndo={handleUndo}
          onRedo={handleRedo}
          onApplyTemplate={applyTemplate}
          onSetDialogOpen={setDialogOpen}
        />

        <div className={`flex p-0 w-full ${isPc ? 'flex-col xl:flex-row' : 'md:flex-row'}`}>
          <div className="w-full overflow-hidden">
            <canvas ref={canvasRef} className="w-full rounded-md border border-gray-300" />
          </div>
          
          {/* 替换属性面板 */}
          <PropertyPanel
            isPc={isPc}
            canvas={canvas}
            selectedObject={selectedObject}
            bgColor={bgColor}
            textItem={textItem}
            imageItem={imageItem}
            fontOptions={fontOptions}
            onBgColorChange={setBgColor}
            onLinearBgColorChange={changeLinearBgColor}
            onTextItemChange={setTextItem}
            onImageItemChange={setImageItem}
          />
        </div>
      </div>
    </TooltipProvider>
  </div>
);
};

export default HomePage;